﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Umbraco.Forms.Core;
using Umbraco.Forms.Data.Storage;
using System.Web.UI.WebControls;
using System.Web.UI;


namespace ContourStrikesAgain.FieldSettingTypes
{
    public class ScoreMapper : FieldSettingType
    {
        private Panel p = new Panel();
        private string _val = "";

        public override string Value
        {
            get
            {
                return _val;
            }
            set
            {
                _val = value;
            }
        }

        public override System.Web.UI.WebControls.WebControl RenderControl(Umbraco.Forms.Core.Attributes.Setting sender, Form form)
        {
            if (!string.IsNullOrEmpty(HttpContext.Current.Request["scoremapperValues"]))
                _val = HttpContext.Current.Request["scoremapperValues"];

            Dictionary<string, int> scores = new Dictionary<string, int>();

            foreach (string mapping in _val.Split(';'))
            {
                int weight = 0;
                if (!string.IsNullOrEmpty(mapping) && mapping.Split(',').Length > 0)
                    scores.Add(mapping.Split(',')[0], int.TryParse(mapping.Split(',')[1], out weight) ? weight : 0);
            }

            string html = "<div id='scoreMapper'>";

            foreach (Field f in form.AllFields)
            {
                if (f.FieldType.SupportsPrevalues && f.PreValueSource.Type.GetPreValues(f).Count > 0)
                {
                    html += string.Format("<div class='scoreMapperField' style='width:400px'><small>{0}</small>", f.Caption);

                    foreach (PreValue pv in f.PreValueSource.Type.GetPreValues(f))
                    {
                        html += string.Format("<div class='scoreMapperFieldPrevalue'><span>{0}</span>", pv.Value);
                        html += string.Format("<input type='hidden' class='key' value='{0}'/>", pv.Id);
                        html += string.Format("&nbsp;<input type='text' class='value' value='{0}'/>", scores.ContainsKey(pv.Id.ToString()) ? scores[pv.Id.ToString()].ToString() : "0");

                        html += "</div>";
                    }

                    html += "</div>";
                }
            }

            html += "<input type='hidden' id='scoreMapperValues' value='" + _val + "' name='scoreMapperValues'/>";
            html += "</div>";

            System.Web.UI.Page page = (System.Web.UI.Page)HttpContext.Current.Handler;

            page.ClientScript.RegisterClientScriptInclude(
                "ContourStrikesAgain.Resources.Scripts.scoreMapper.js",
                page.ClientScript.GetWebResourceUrl(typeof(ScoreMapper), "ContourStrikesAgain.Resources.Scripts.scoreMapper.js"));

            p.Controls.Add(new LiteralControl(html));

            return p;
        }


    }
}